package zpe.genericcrud.jsf.view.converter;

import java.text.NumberFormat;
import java.util.Locale;
import java.util.regex.Pattern;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import zpe.genericcrud.jsf.view.bean.FacesUtils;

@FacesConverter("myDoubleConverter")
public class MyDoubleConverter implements Converter {

public Object getAsObject(FacesContext context, UIComponent component, String value) {
		
		if(value == null || value.trim().equals("")){
			return 0.0D;
		 }
		
		value = value.replace("%", "");	
		
		if(value.equals("00,0")) 
				value = "0.00"; 
			
			Boolean matcher = Pattern.matches("[0-9]+([.,][0-9]{2,3})?",value);
				if(matcher){
					value = value.replace(",", ".");
					return new Double(value);
				}
				else{
					FacesUtils.addErrorMessage("Formato Invalido");
					throw new ConverterException();
				}
	}

	public String getAsString(FacesContext context, UIComponent component, Object object) {
		
		if(object == null || object.toString().trim().equals("")){
			 return "0.00";
		 }
		 else{
			 NumberFormat nF = NumberFormat.getInstance(new Locale("pt", "BR"));
			 nF.setMaximumFractionDigits(2);
			 nF.setMinimumFractionDigits(2);
			 return nF.format(Double.valueOf(object.toString()));
		 }
	}  	
}